if exists (select 1
          from sysobjects
          where  id = object_id('bd_fn_numToMin3')
          and type in ('IF', 'FN', 'TF'))
   drop function bd_fn_numToMin3
go


create function bd_fn_numToMin3 (@min INT)
RETURNS VARCHAR(10)
BEGIN

  IF (ISNULL(@min, 0) < 0)
    SET @min = ABS(@min)

  IF (ISNULL(@min, 0) >= 1440)
    SET @min = @min - 1440

  IF (ISNULL(@min, 0) = 0)
    RETURN '00:00';

  DECLARE @result VARCHAR(20) = ''

  IF (@min < 0)
  BEGIN
    SET @result = '-' + RIGHT('00' + CAST(@min / 60 AS VARCHAR(20)), 2) + ':' + RIGHT('00' + CAST(@min % 60 AS VARCHAR(20)), 2)
  END
  ELSE
  BEGIN
    SET @result = + RIGHT('00' + CAST(@min / 60 AS VARCHAR(20)), 2) + ':' + RIGHT('00' + CAST(@min % 60 AS VARCHAR(20)), 2)
  END

  RETURN @result
END
go
